import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Platform } from 'react-native';

// 根据运行环境动态设置API地址
let API_URL = 'http://localhost:3000'; // 默认为Web环境

// 根据平台选择合适的API地址
if (Platform.OS === 'android') {
  API_URL = 'http://10.0.2.2:3000'; // Android模拟器
} else if (Platform.OS === 'ios') {
  API_URL = 'http://localhost:3000'; // iOS模拟器
}

// 如果需要真机调试，取消下面注释并设置为计算机的实际IP地址
// API_URL = 'http://192.168.1.100:3000';

console.log(`当前运行环境: ${Platform.OS}, API地址: ${API_URL}`);

const api = axios.create({
  baseURL: API_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器，添加token到请求头
api.interceptors.request.use(
  async (config) => {
    const token = await AsyncStorage.getItem('userToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器，处理错误
api.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 处理错误，例如401未授权时自动登出
    if (error.response && error.response.status === 401) {
      // 清除本地存储的token
      AsyncStorage.removeItem('userToken');
    }
    return Promise.reject(error);
  }
);

// 认证相关API
export const authAPI = {
  // 用户注册
  register: async (name: string, age: string, email: string, password: string) => {
    try {
      console.log('API 注册请求开始，发送数据:', { name, age, email });
      // 将 age 转换为数字，因为后端期望接收数字类型
      const ageNum = parseInt(age);
      if (isNaN(ageNum)) {
        throw new Error('年龄必须是有效的数字');
      }
      
      const response = await api.post('/auth/register', {
        name,
        age: ageNum, // 发送数字类型的年龄
        email,
        password,
      });
      console.log('API 注册请求成功，响应:', response);
      return response;
    } catch (error: any) {
      console.error('API 注册请求错误:', error);
      console.error('错误详情:', error.response?.data || error.message);
      throw error;
    }
  },

  // 用户登录
  login: async (email: string, password: string) => {
    try {
      const response = await api.post('/auth/login', {
        email,
        password,
      });
      return response;
    } catch (error: any) {
      console.error('Login error:', error);
      throw error;
    }
  },

  // 获取用户资料
  getProfile: async () => {
    try {
      const response = await api.get('/auth/profile');
      return response;
    } catch (error: any) {
      console.error('Get profile error:', error);
      throw error;
    }
  },

  // 更新用户资料
  updateProfile: async (userId: number, data: any, preferences: any) => {
    try {
      console.log('准备发送更新请求:', { userId, data, preferences });
      const response = await api.patch(`/users/profile/${userId}`, {
        ...data,
        preferences,
      });
      console.log('更新请求成功，响应:', response);
      return response;
    } catch (error: any) {
      console.error('Update profile error:', error);
      console.error('错误详情:', error.response?.data || error.message);
      throw error;
    }
  },

  // 修改密码
  changePassword: async (userId: number, currentPassword: string, newPassword: string) => {
    try {
      const response = await api.post(`/users/change-password/${userId}`, {
        currentPassword,
        newPassword,
      });
      return response;
    } catch (error: any) {
      console.error('Change password error:', error);
      throw error;
    }
  },
};

// 聊天相关API
export const chatAPI = {
  // 获取最近聊天列表
  getConversations: async () => {
    try {
      const response = await api.get('/chat/conversations');
      return response;
    } catch (error: any) {
      console.error('Get conversations error:', error);
      throw error;
    }
  },

  // 获取与特定用户的聊天记录
  getConversation: async (userId: string) => {
    try {
      const response = await api.get(`/chat/conversation/${userId}`);
      return response;
    } catch (error: any) {
      console.error('Get conversation error:', error);
      throw error;
    }
  },

  // 发送消息
  sendMessage: async (receiverId: number, content: string) => {
    try {
      const response = await api.post('/chat/message', {
        receiverId,
        content,
      });
      return response;
    } catch (error: any) {
      console.error('Send message error:', error);
      throw error;
    }
  },

  // 发送AI消息
  sendAIMessage: async (content: string) => {
    try {
      const response = await api.post('/chat/ai-message', {
        content,
      });
      return response;
    } catch (error: any) {
      console.error('Send AI message error:', error);
      throw error;
    }
  },

  // 标记消息为已读
  markAsRead: async (messageId: number) => {
    try {
      const response = await api.put(`/chat/message/${messageId}/read`);
      return response;
    } catch (error: any) {
      console.error('Mark as read error:', error);
      throw error;
    }
  },

  // 获取未读消息数量
  getUnreadCount: async () => {
    try {
      const response = await api.get('/chat/unread-count');
      return response;
    } catch (error: any) {
      console.error('Get unread count error:', error);
      throw error;
    }
  },
};

export default api;